package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.model.po.Admin;
import com.cskaoyan.mall.model.bo.admin.AdminChangePwdBo;
import com.cskaoyan.mall.model.bo.admin.AdminLoginBo;
import com.cskaoyan.mall.model.vo.admin.AdminServletVo;
import com.cskaoyan.mall.service.AdminService;
import com.cskaoyan.mall.service.lmpl.AdminServiceImpl;
import com.cskaoyan.mall.utils.Result;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: AdminService
 * @Description: TODO
 * @Auther 庄左
 * @Date 2022/6/28 17:42
 * @Version
 **/
@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();


    private Gson gson = new Gson();
    private Result result = new Result();

    //获取Json字符串,后续多个方法需要将请求体中封装的对象通过这种方式取出
    private String getJsonString(HttpServletRequest req) throws IOException {
        ServletInputStream inputStream = req.getInputStream();
        //写入字节数组的输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        //转为字符串
        return outputStream.toString("utf-8");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/admin/admin/", "");
        if ("login".equals(replace)) {
            login(req, resp);
        }
        if ("getSearchAdmins".equals(replace)) {
            reaserchByName(req, resp);
        }
        if ("addAdminss".equals(replace)) {
            addAdmins(req, resp);
        }
        if ("updateAdminss".equals(replace)) {
            updateAdminss(req, resp);
        }
        if ("changePwd".equals(replace)) {
            changePed(req, resp);
        }
        if ("logoutAdmin".equals(replace)) {
            logoutAdmin(req, resp);
        }
    }

    private void logoutAdmin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //怎么退出?
        req.getSession().invalidate();

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));

        // login(req,resp);

    }

    /**
     * @Author: 庄左
     * @Description: 更改当前admin自己的密码
     * @DateTime: 2022/7/2 20:39
     */
    private void changePed(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String reqBody = getJsonString(req);
        //拿到json字符串----->java对象
        AdminChangePwdBo adminChangePwdBo = gson.fromJson(reqBody, AdminChangePwdBo.class);
        //获取旧密码，如何获取?
        //nickname不可重复，根据nickname取出旧密码
        //判断旧密码是否正确
        // String oldPwd = (String) req.getServletContext().getAttribute("oldPwd");
        Object oldPwd = req.getSession().getAttribute("oldPwd");
        if (!adminChangePwdBo.getOldPwd().equals(oldPwd)) {
            result.setCode(10000);
            result.setMessage("旧密码错误");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        //判断新密码是否与旧密码相同
        if (adminChangePwdBo.getNewPwd().equals(oldPwd)) {
            result.setCode(10000);
            result.setMessage("新密码不能与旧密码相同");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        //判断新密码是否一致
        if (!adminChangePwdBo.getNewPwd().equals(adminChangePwdBo.getConfirmPwd())) {
            result.setCode(10000);
            result.setMessage("请保持确认新密码一致！");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        adminService.changePwd(adminChangePwdBo);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
        //修改完退出
        // resp.getWriter().println("请重新登录");
        // resp.setHeader("refresh","2;url="+req.getContextPath()+"/api/admin/admin/logoutAdmin");
        // resp.getWriter().println("<a href='"+req.getContextPath()+"/api/admin/admin/logoutAdmin");
    }


    /**
     * @Author: 庄左
     * @Description: 修改任意admin的信息，不应该让普通管理员拥有该项权限
     * TODO：权限控制
     * @DateTime: 2022/7/2 20:47
     */
    private void updateAdminss(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        AdminLoginBo adminLoginBo = gson.fromJson(getJsonString(req), AdminLoginBo.class);
        adminService.updateAdmins(adminLoginBo);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 新增admin
     * TODO:验证输入是否合法
     * @DateTime: 2022/7/2 20:48
     */
    private void addAdmins(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        AdminLoginBo adminLoginBo = gson.fromJson(getJsonString(req), AdminLoginBo.class);
        adminService.addAdmins(adminLoginBo);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));

    }

    /**
    * @Author: 庄左
    * @Description: 通过名字和昵称查找管理员，模糊查询
     * TODO：该查询会显示管理员密码，应该加以屏蔽
    * @DateTime: 2022/7/2 20:54
    */
    private void reaserchByName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        AdminLoginBo adminLoginBo = gson.fromJson(getJsonString(req), AdminLoginBo.class);
        List<AdminLoginBo> admin = adminService.selectByName(adminLoginBo);
        result.setCode(0);
        result.setData(admin);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 登录，系统的入口，未登录不可进入后台
     * @DateTime: 2022/7/2 21:04
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取管理员输入的账号密码
        //获取请求体
        AdminLoginBo adminLoginBo = gson.fromJson(getJsonString(req), AdminLoginBo.class);


        if (StringUtils.isEmpty(adminLoginBo.getEmail())) {
            result.setCode(10000);
            result.setMessage("用户名、密码不能为空");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        Admin admin = adminService.login(adminLoginBo);
        if (admin != null) {
            //登录成功
            result.setCode(0);
            AdminServletVo adminServletVo = new AdminServletVo();
            adminServletVo.setName(admin.getNickname());
            adminServletVo.setToken(admin.getNickname());
            //登陆成功进行这一步
            //将旧密码，用户名存入contex域/session域
            //这一步为之后的修改自身密码时与用户输入的旧密码做比对
            // req.getServletContext().setAttribute("nameToken", adminLoginBo.getEmail());
            // req.getServletContext().setAttribute("oldPwd", adminLoginBo.getPwd());
            HttpSession session = req.getSession();
            session.setAttribute("name",adminLoginBo.getEmail());
            session.setAttribute("oldPwd",adminLoginBo.getPwd());

            result.setData(adminServletVo);
            resp.getWriter().println(gson.toJson(result));
        } else {
            result.setCode(10000);
            result.setMessage("用户名、密码错误");
            resp.getWriter().println(gson.toJson(result));
            return;
        }


    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/admin/admin/", "");
        if ("allAdmins".equals(replace)) {
            reaserch(req, resp);
        }
        if ("deleteAdmins".equals(replace)) {
            deleteAdmins(req, resp);
        }
        if ("getAdminsInfo".equals(replace)) {
            getAdminsInfo(req, resp);
        }

    }

    private void getAdminsInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求参数id
        Integer id = Integer.valueOf(req.getParameter("id"));

        Admin admin = adminService.selectById(id);

        AdminLoginBo adminLoginBo = new AdminLoginBo();
        adminLoginBo.setId(admin.getId());
        adminLoginBo.setEmail(admin.getUsername());
        adminLoginBo.setNickname(admin.getNickname());
        adminLoginBo.setPwd(admin.getPassword());

        result.setCode(0);
        result.setData(adminLoginBo);
        resp.getWriter().println(gson.toJson(result));

    }

    private void deleteAdmins(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        //TODO:实现超级管理员的功能
        Object nameToken = req.getServletContext().getAttribute("nameToken");
        // Integer myid;
        // if (myid >= 3 && !myid.equals(id)) {
        //     result.setCode(1000);
        //     result.setMessage("您不是超级管理员，无权删除他人的账号");
        //     resp.getWriter().println(gson.toJson(result));
        //     return;
        // }
        if (id <= 3) {
            result.setCode(1000);
            result.setMessage("超级管理员账号不可删除！");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        adminService.deleteAdmins(id);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    private void reaserch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<AdminLoginBo> admins = adminService.search();
        result.setCode(0);
        result.setData(admins);
        resp.getWriter().println(gson.toJson(result));
    }

}

